<template>
  <div class="doctor-handle">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <!-- 基础信息 -->
      <el-divider content-position="left">基础信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="医生工号" prop="doctorNo">
            <el-input v-model="form.doctorNo" placeholder="请输入医生工号" clearable />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="医生姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入医生姓名" clearable />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username" placeholder="请输入登录用户名" clearable />
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="!isEdit">
          <el-form-item label="登录密码" prop="password">
            <el-input v-model="form.password" type="password" placeholder="请输入登录密码" clearable show-password />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="所属科室" prop="departmentId">
            <el-tree-select
              v-model="form.departmentId"
              placeholder="请选择科室"
              style="width: 100%"
              filterable
              :data="departmentTree"
              node-key="id"
              :props="{
                label: 'name',
                value: 'id',
                children: 'children'
              }"
              check-strictly
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职称" prop="title">
            <el-select v-model="form.title" placeholder="请选择职称" style="width: 100%">
              <el-option label="主任医师" :value="1" />
              <el-option label="副主任医师" :value="2" />
              <el-option label="主治医师" :value="3" />
              <el-option label="住院医师" :value="4" />
              <el-option label="实习医师" :value="5" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="form.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生日期" prop="birthDate">
            <el-date-picker
              v-model="form.birthDate"
              type="date"
              placeholder="请选择出生日期"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 联系信息 -->
      <el-divider content-position="left">联系信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱地址" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="地址" prop="address">
            <el-input v-model="form.address" placeholder="请输入详细地址" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="紧急联系人" prop="emergencyContact">
            <el-input v-model="form.emergencyContact" placeholder="请输入紧急联系人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="紧急联系电话" prop="emergencyPhone">
            <el-input v-model="form.emergencyPhone" placeholder="请输入紧急联系电话" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 专业信息 -->
      <el-divider content-position="left">专业信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="工作年限" prop="workYears">
            <el-input-number
              v-model="form.workYears"
              :min="0"
              :max="50"
              placeholder="请输入工作年限"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学历" prop="education">
            <el-select v-model="form.education" placeholder="请选择学历" style="width: 100%">
              <el-option label="博士" :value="1" />
              <el-option label="硕士" :value="2" />
              <el-option label="本科" :value="3" />
              <el-option label="大专" :value="4" />
              <el-option label="其他" :value="5" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="毕业院校" prop="graduateSchool">
            <el-input v-model="form.graduateSchool" placeholder="请输入毕业院校" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="执业证书号" prop="licenseNumber">
            <el-input v-model="form.licenseNumber" placeholder="请输入医师执业证书号" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="专业特长" prop="specialty">
            <el-input
              v-model="form.specialty"
              type="textarea"
              :rows="3"
              placeholder="请输入专业特长"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="个人简介" prop="introduction">
            <el-input
              v-model="form.introduction"
              type="textarea"
              :rows="3"
              placeholder="请输入个人简介"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <div class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        确定
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/api/request'

// 定义props
const props = defineProps({
  doctorData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  },
  departmentTree: {
    type: Array,
    default: () => []
  }
})

// 定义emits  
const emit = defineEmits(['close'])

// 响应式数据
const submitting = ref(false)
const formRef = ref(null)
const submitLoading = ref(false)

// 表单数据
const form = reactive({
  id: null,
  username: '',
  password: '',
  doctorNo: '',
  name: '',
  departmentId: null,
  title: null,
  gender: 1,
  birthDate: '',
  phone: '',
  email: '',
  address: '',
  emergencyContact: '',
  emergencyPhone: '',
  workYears: null,
  education: null,
  graduateSchool: '',
  licenseNumber: '',
  specialty: '',
  introduction: '',
  remark: '',
  status: 1
})

// 动态验证规则
const rules = computed(() => {
  const baseRules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    doctorNo: [
      { required: true, message: '请输入医生工号', trigger: 'blur' }
    ],
    name: [
      { required: true, message: '请输入医生姓名', trigger: 'blur' }
    ],
    departmentId: [
      { required: true, message: '请选择所属科室', trigger: 'change' }
    ],
    title: [
      { required: true, message: '请选择职称', trigger: 'change' }
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    email: [
      { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    workYears: [
      { required: true, message: '请输入工作年限', trigger: 'blur' }
    ]
  }

  // 新增模式下密码必填，编辑模式下密码可选
  if (!props.isEdit) {
    baseRules.password = [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
    ]
  } else if (form.password) {
    baseRules.password = [
      { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
    ]
  }

  return baseRules
})


// 处理取消
const handleCancel = () => {
  emit('close')
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    const isEdit = !!form.id
    const url = '/admin/doctor'
    const method = isEdit ? 'put' : 'post'
    
    // 准备提交数据
    const submitData = { ...form }
    
    // 编辑模式下，如果密码为空，则不发送密码字段
    if (isEdit && !submitData.password) {
      delete submitData.password
    }
    
    const response = await request[method](url, submitData)
    
    if (response.code === 200) {
      ElMessage.success(isEdit ? '更新成功' : '添加成功')
      emit('close', 'success')
    } else {
      ElMessage.error(response.message || (isEdit ? '更新失败' : '添加失败'))
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitting.value = false
  }
}

// 组件挂载时初始化
onMounted(() => {
  if (props.isEdit && props.doctorData) {
    Object.assign(form, props.doctorData)
  }
})
</script>

<style scoped>
.doctor-handle {
  padding: 20px 0;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-form-item__label) {
  font-weight: 600;
}

:deep(.el-divider__text) {
  font-weight: 600;
  color: #409eff;
}
</style> 